package com.landscope.issue.service.applet;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.landscope.issue.controller.api.dto.LoginDto;
import com.landscope.issue.controller.api.dto.WxPhoneLoginDto;
import com.landscope.issue.controller.base.ResponseResult;
import com.landscope.issue.controller.wx.param.AppletAuthParam;
import com.landscope.issue.controller.wx.param.AppletBandingParam;
import com.landscope.issue.entity.Token;
import com.landscope.issue.entity.User;
import com.landscope.issue.entity.UserParam;
import com.landscope.issue.mapper.TokenMapper;
import com.landscope.issue.mapper.UserParamMapper;
import com.landscope.issue.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApiAppletLoginService {

    private static final String GET_OPENID_URL = "https://api.weixin.qq.com/wxa/getpluginopenpid";

    private String wx_app_id = "wx08af4de0a76d53cd";
    private String wx_app_secret = "462d766a9a80e516e7a6f2c1cf39dddf";

    @Value("${center_login_url}")
    private String centerLoginUrl;

    @Resource
    private TokenMapper tokenMapper;

    @Resource
    private UserParamMapper userParamMapper;

    public ResponseResult<LoginDto> banding(AppletBandingParam param) {
        User user = TokenUtil.verifyAuthority(param.getAccessToken(), null);
        UserParam userParam = userParamMapper.findByAccount(user.getAccount());
        if (userParam == null) {
            userParam = new UserParam();
            userParam.setOpenid(param.getOpenId());
            userParam.setAccount(user.getAccount());
            userParamMapper.insertSelective(userParam);
        } else {
            userParam.setOpenid(param.getOpenId());
            userParamMapper.updateByPrimaryKeySelective(userParam);
        }
        return new ResponseResult().success();
    }


    public ResponseResult<LoginDto> auth(AppletAuthParam param) {
        Token token = tokenMapper.findByName("weixin");
        if (token == null) {
            return new ResponseResult().error().message("服务器AccessToken不存在");
        }
//        String url = GET_OPENID_URL + "?access_token=" + token.getAccessToken() + "&code=" + param.getCode();
//        String url = GET_OPENID_URL + "?access_token=" + token.getAccessToken();
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + wx_app_id +
                "&secret=" + wx_app_secret +
                "&js_code=" + param.getCode() + "&grant_type=authorization_code";

        Map<String, Object> map = new HashMap<>();
        map.put("code", param.getCode());

        log.info("获取微信openId请求:{}", url);
        String res = HttpUtil.get(url);
        log.info("获取微信openId结果:{}", res);

        JSONObject obj = JSONObject.parseObject(res);
        if (obj.get("openid") != null) {
            String openId = obj.getString("openid");
            User user = TokenUtil.verifyAuthority(param.getAccessToken(), null);
            // 保存用户的openId
            UserParam userParam = userParamMapper.findByAccount(user.getAccount());
            if (userParam == null) {
                userParam = new UserParam();
                userParam.setOpenid(openId);
                userParam.setAccount(user.getAccount());
                userParamMapper.insertSelective(userParam);
            } else {
                userParam.setOpenid(openId);
                userParamMapper.updateByPrimaryKeySelective(userParam);
            }
        }
        return new ResponseResult().success();
    }

    public ResponseResult<WxPhoneLoginDto> WxPhoneLogin(AppletAuthParam param) {
        Token token = tokenMapper.findByName("weixin");
        if (token == null) {
            return new ResponseResult().error().message("服务器AccessToken不存在");
        }
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?" +
                "access_token=" + token.getAccessToken();

        Map<String, Object> map = new HashMap<>();
        map.put("code", param.getCode());

        log.info("获取微信手机号请求:{}", url);
        log.info("获取微信手机号参数:{}", JSONObject.toJSONString(map));
        String res = HttpUtil.post(url,JSONObject.toJSONString(map));
        log.info("获取微信手机号结果:{}", res);

        JSONObject obj = JSONObject.parseObject(res);
        if (obj.get("phone_info") != null) {
            JSONObject phoneObj = obj.getJSONObject("phone_info");
            String purePhoneNumber = phoneObj.getString("purePhoneNumber");

            // 管理端授权
            Map<String,String> centerLoginParams = new HashMap<>();
            centerLoginParams.put("account",purePhoneNumber);
            String centerLoginRes = HttpUtil.post(centerLoginUrl,JSONObject.toJSONString(centerLoginParams));

            JSONObject centerLoginObj = JSONObject.parseObject(centerLoginRes);
            //{"errcode":0,"errmsg":"ok","phone_info":{"phoneNumber":"15308083114","purePhoneNumber":"15308083114","countryCode":"86","watermark":{"timestamp":1677252016,"appid":"wx08af4de0a76d53cd"}}}
            // 验证access_token
            if(centerLoginObj.getInteger("code") != 0){
                return new ResponseResult<WxPhoneLoginDto>().error().message(centerLoginObj.getString("message"));
            }
            String accessToken = centerLoginObj.getJSONObject("data").getString("accessToken");
            User user = TokenUtil.verifyAuthority(accessToken, null);
            // 生成token
            String loginToken = TokenUtil.createToken(user.getId(), user.getName(), user.getRolePermissionCode());
            log.info("登录返回token:{}",token);
            return new ResponseResult<WxPhoneLoginDto>().success().setData(new WxPhoneLoginDto(loginToken,accessToken,user.getAccount(),user.getUnitName()));
        }

        return new ResponseResult().error().message("获取手机号失败");


//        String purePhoneNumber = "15882781032";
//        // 管理端授权
//        Map<String, String> centerLoginParams = new HashMap<>();
//        centerLoginParams.put("account", purePhoneNumber);
//        String centerLoginRes = HttpUtil.post(centerLoginUrl, JSONObject.toJSONString(centerLoginParams));
//        System.out.println("centerLoginRes:"+centerLoginRes);
//
//        JSONObject centerLoginObj = JSONObject.parseObject(centerLoginRes);
//        // 验证access_token
//        User user = TokenUtil.verifyAuthority(centerLoginObj.getJSONObject("data").getString("accessToken"), null);
//        // 生成token
//        String loginToken = TokenUtil.createToken(user.getId(), user.getName(), user.getRolePermissionCode());
//        log.info("登录返回token:{}", token);
//        return new ResponseResult<LoginDto>().success().setData(new LoginDto(loginToken, user.getAccount(), user.getUnitName()));
    }
}
